package com.astrofizzbizz.stoneedgegui.monitor;

import javax.swing.JPanel;
import javax.swing.JProgressBar;

import com.astrofizzbizz.stoneedgegui.utilities.StoneEdgeIIIException;



public class DomeLightControl implements Runnable
{
	private boolean lightsOn = false;
	private JProgressBar lightStayOnProgress = null;
	private JPanel lightStayOnProgressPanel = null;
	private TelescopeMonitorPanel telescopeMonitorPanel;

	public DomeLightControl(TelescopeMonitorPanel telescopeMonitorPanel)
	{
		this.telescopeMonitorPanel = telescopeMonitorPanel;
	}
	void lightSwitch(boolean turnOn)
	{
		if(turnOn)
		{
			if(lightsOn)
			{
				lightStayOnProgress.setValue(60);
				turnDomeLightControlOn(true);
			}
			else
			{
				lightsOn = true;
				lightStayOnProgressPanel.setVisible(true);
				lightStayOnProgress.setValue(60);
				turnDomeLightControlOn(true);
			}
		}
		else
		{
			if(lightsOn)
			{
				lightsOn = false;
				lightStayOnProgressPanel.setVisible(false);
				turnDomeLightControlOn(false);
			}
			else
			{
				turnDomeLightControlOn(false);
			}
			lightStayOnProgress.setValue(0);
		}
	}
	private void turnDomeLightControlOn(boolean on)
	{
		String command = "tx lamps all=off";
		if (on) command = "tx lamps all=on";
	    String[] response = {"",""};
		try {response = telescopeMonitorPanel.getStoneEdgeIIIGui().getStoneEdgeIIITunnel().executeCommand(command, 1024);} catch (StoneEdgeIIIException e) {e.printStackTrace();} 
		telescopeMonitorPanel.getStatusBar().setText(response[0].replace("\n", " "));
		
	}
	public boolean isLightsOn() {return lightsOn;}
	public void setLightsOn(boolean lightsOn) {this.lightsOn = lightsOn;}
	public JProgressBar getLightStayOnProgress() {return lightStayOnProgress;}
	public void setLightStayOnProgress(JProgressBar lightStayOnProgress) {this.lightStayOnProgress = lightStayOnProgress;}
	public void setLightStayOnProgressPanel(JPanel lightStayOnProgressPanel) {this.lightStayOnProgressPanel = lightStayOnProgressPanel;}
	public JPanel getLightStayOnProgressPanel() {return lightStayOnProgressPanel;}
	@Override
	public void run() 
	{
		while(true)
		{
			try {Thread.sleep(1 * 1000);} catch (InterruptedException e) {;}
			if (lightsOn)
			{
				int progress = lightStayOnProgress.getValue();
				if (progress == 1)
				{
					lightSwitch(false);
				}
				lightStayOnProgress.setValue(progress - 1);
			}
		}
	}
	
}
